package cn.itsource.exam.controller;

import cn.itsource.exam.domain.Role;
import cn.itsource.exam.query.RoleQueryVo;
import cn.itsource.exam.service.IRoleService;
import cn.itsource.exam.util.AjaxResult;
import cn.itsource.exam.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;

    @PostMapping("/roleList")
    public  PageList<Role> getRoles(@RequestBody RoleQueryVo queryVo){
        System.out.println("++++++++++++++++++++++++++");
        PageList<Role> rolePageList= roleService.selectRole(queryVo);
        return rolePageList;
    }

    @PostMapping("/roleInfo")
    public AjaxResult save(@RequestBody Role role){
        if(role==null){
            return AjaxResult.error("无法获取保存的角色信息");
        }
        try {
            if(role.getId()==null){
                Role role1 = roleService.selectRoleByName(role);
                if (role1 != null){
                    return AjaxResult.error("名字已重复！");
                };
                roleService.insertRole(role);
            }else{
                roleService.updateRole(role);
            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    @DeleteMapping("/roleInfo/{roleId}")
    public AjaxResult delete(@PathVariable("roleId") Long roleId){
        try {
            roleService.deleteRole(roleId);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    @PutMapping("/roleInfo")
    public AjaxResult batchDeleta(@RequestBody Long[] roleIds){
        try {
            roleService.batchDeleteRole(roleIds);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

}
